package com.sunxu.ioc.container;

import com.sunxu.ioc.domain.ImportantUser;
import com.sunxu.ioc.domain.User;
import org.springframework.beans.factory.BeanFactory;
import org.springframework.beans.factory.ListableBeanFactory;
import org.springframework.beans.factory.support.DefaultListableBeanFactory;
import org.springframework.beans.factory.xml.XmlBeanDefinitionReader;
import org.springframework.context.annotation.AnnotationConfigApplicationContext;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import javax.crypto.Mac;
import java.util.Map;

/**
 * @author 孙许
 * @version 1.0
 * @date 2020/4/12 2:47 下午
 */
@Configuration
public class AnnotationApplicationAsIocContainerDemo {
    public static void main(String[] args) {
        // 创建BeanFactory容器
        DefaultListableBeanFactory beanFactory  = new DefaultListableBeanFactory();
        AnnotationConfigApplicationContext applicationContext = new AnnotationConfigApplicationContext();
        // 将当前类作为配置类
        applicationContext.register(AnnotationApplicationAsIocContainerDemo.class);
        applicationContext.refresh();
        // 依赖查找集合对象
        lookupByCollectionType(applicationContext);
        applicationContext.close();
    }

    @Bean
    public User user() {
        User user = new User();
        user.setId(5L);
        user.setName("Mac");
        return user;
    }

    /**
     * 按照集合类型查找
     *
     * @param beanFactory
     */
    private static void lookupByCollectionType(BeanFactory beanFactory) {
        if (beanFactory instanceof ListableBeanFactory) {
            ListableBeanFactory listableBeanFactory = (ListableBeanFactory) beanFactory;
            Map<String, User> beansOfType = listableBeanFactory.getBeansOfType(User.class);
            System.out.println(beansOfType);
        }
    }
}
